package controllers

import (
	"encoding/json"
	"os"
	"path"
	"runtime"
	"strconv"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"
	// "github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"

	"demo0606/modules"
)

type Users struct{}
type MyClaims struct {
	Username string
	jwt.StandardClaims
}

var jwtKey = []byte("123456")

func (con Users) LoginOut(c *gin.Context) {
	// session := sessions.Default(c)
	// session.Delete("userInfo")
	// session.Save()
	c.JSON(200, gin.H{
		"success": true,
		"message": "退出登录成功",
	})
}
func (con Users) Dologin(c *gin.Context) {
	type userInfo struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}
	info := &userInfo{}
	c.BindJSON(&info)

	// username := c.PostForm("username")
	// password := c.PostForm("password")
	user := []modules.User{}
	user2 := []modules.User{}
	err := modules.DB.Model(&modules.User{}).Preload("Roles.Auths").Where("Username=? AND Password=?", info.Username, info.Password).Find(&user).Error
	modules.DB.Table("user").Select("*").Preload("Roles.Auths").Where("Username=? AND Password=?", info.Username, info.Password).Find(&user2)
	if err == nil {
		if len(user) > 0 {
			userList, _ := json.Marshal(user)
			jwt, bl := CreateJWT(c, string(userList))

			if bl == false {
				var menuList = []interface{}{}
				var newMap = map[int]int{}
				roleList := user[0].Roles
				for _, item := range roleList {
					for _, obj := range item.Auths {
						_, ok := newMap[obj.Id]
						if !ok {
							menuList = append(menuList, obj)
							newMap[obj.Id] = obj.Id
						}
					}
				}

				// println("newMap", len(newMap))
				c.JSON(200, gin.H{
					"success":  true,
					"message":  "登录成功",
					"username": info.Username,
					"menuList": menuList,
					"token":    jwt,
				})
			} else {
				c.JSON(200, gin.H{
					"success": false,
					"message": "token生成失败",
				})
			}

		} else {
			c.JSON(401, gin.H{
				"success": false,
				"message": "用户名或者密码错误",
			})
		}
	} else {
		c.JSON(500, gin.H{
			"success": false,
			"message": "登录失败",
		})
	}

}

func CreateJWT(c *gin.Context, name string) (string, bool) {

	var expireTime = time.Now().Add(20 * time.Hour).Unix()
	myClient := MyClaims{
		name,
		jwt.StandardClaims{
			ExpiresAt: expireTime,
		},
	}
	tokenObj := jwt.NewWithClaims(jwt.SigningMethodHS256, myClient)
	tokenStr, err := tokenObj.SignedString(jwtKey)
	if err == nil {
		// c.JSON(200, gin.H{
		// 	"success": true,
		// 	"message": "生成token成功",
		// 	"token":   tokenStr,
		// })
		return tokenStr, false
	} else {
		// c.JSON(200, gin.H{
		// 	"success": false,
		// 	"message": "生成token失败",
		// })
		return "", true
	}
}

func (user Users) ChangeUserRole(c *gin.Context) {
	userId := c.PostForm("user_id")
	roleId := c.PostForm("role_id")
	roleIdList := strings.Split(roleId, ",")
	userRole := modules.UserRole{}
	err := modules.DB.Where("user_id=?", userId).Delete(&userRole).Error
	userIdNum, _ := strconv.Atoi(userId)
	for _, v := range roleIdList {
		userRole := modules.UserRole{}
		userRole.UserId = userIdNum
		num, _ := strconv.Atoi(v)
		userRole.RoleId = num
		modules.DB.Create(&userRole)
	}
	if err != nil {
		c.JSON(200, gin.H{
			"success": false,
			"message": "修改角色失败",
		})
	} else {
		c.JSON(200, gin.H{
			"success": true,
			"message": "修改角色成功",
		})
	}

}

func (user Users) GetUserList(c *gin.Context) {
	page := c.DefaultQuery("page", "0")
	pageSize := c.DefaultQuery("pageSize", "10")
	userName := c.DefaultQuery("userName", "")
	userList := []modules.User{}
	p, _ := strconv.Atoi(page)
	s, _ := strconv.Atoi(pageSize)
	p = p - 1
	var count int64
	if userName == "" {
		modules.DB.Preload("Roles").Limit(s).Offset(p * s).Find(&userList).Limit(-1).Offset(-1).Count(&count)
	} else {
		modules.DB.Where("username LIKE ?", "%"+userName+"%").Preload("Roles").Find(&userList).Limit(-1).Offset(-1).Count(&count)
	}
	c.JSON(200, gin.H{
		"list":     userList,
		"page":     page,
		"total":    count,
		"pageSize": pageSize,
	})
}

func (user Users) AddUser(c *gin.Context) {
	userName := c.PostForm("userName")
	age := c.PostForm("age")
	age1, _ := strconv.Atoi(age)
	email := c.PostForm("email")
	timeNow := time.Now().Unix()
	timeNow2 := int(timeNow)
	user1 := modules.User{
		Username: userName,
		Password: "123456",
		Age:      age1,
		Email:    email,
		AddTime:  timeNow2,
	}
	err := modules.DB.Create(&user1).Error
	if err == nil {
		c.JSON(200, gin.H{
			"success":  true,
			"userName": userName,
			"age":      age,
			"email":    email,
		})
	} else {
		c.JSON(500, gin.H{
			"success": false,
			"message": "新增用户失败",
		})
	}

}

func (user Users) UpdateUser(c *gin.Context) {
	userName := c.PostForm("userName")
	age := c.PostForm("age")
	age1, _ := strconv.Atoi(age)
	email := c.PostForm("email")
	id := c.PostForm("id")
	modules.DB.Model(&modules.User{}).Where("Id = ?", id).Updates(map[string]interface{}{"Username": userName, "Age": age1, "Email": email})
	c.JSON(200, gin.H{
		"success": true,
		"id":      id,
		"message": "修改数据成功",
	})
}

func (user Users) DeleteUser(c *gin.Context) {
	id := c.PostForm("id")
	modules.DB.Delete(&modules.User{}, id)
	c.JSON(200, gin.H{
		"success": true,
		"id":      id,
		"message": "删除数据成功",
	})
}

func (user Users) TestTemplate(c *gin.Context) {
	userList := []modules.User{}
	modules.DB.Find(&userList)
	c.HTML(200, "users.html", gin.H{
		"userList": userList,
	})
}

func (user Users) UploadPic(c *gin.Context) {
	file, err := c.FormFile("file")
	println("err", err)
	if err == nil {
		dsn := path.Join("./static/imgs/", file.Filename)
		if err := c.SaveUploadedFile(file, dsn); err == nil {
			c.JSON(200, gin.H{
				"success": true,
				"message": "上传成功",
				"url":     "/static/imgs/" + file.Filename,
			})
		} else {
			c.JSON(500, gin.H{
				"success": false,
				"message": "上传失败",
			})
		}

	} else {
		c.JSON(500, gin.H{
			"success": false,
			"message": "上传失败",
		})
	}

}

func (user Users) UploadEventsPic(c *gin.Context) {
	// file, err := c.FormFile("file")
	file, err := c.FormFile("wangeditor-uploaded-image")
	if err == nil {
		dsn := path.Join("./static/imgs/events", file.Filename)
		if err := c.SaveUploadedFile(file, dsn); err == nil {
			type Data struct {
				Url string `json:"url"`
			}
			data := Data{}
			goos := runtime.GOOS
			if goos == "darwin" {
				data.Url = "http://localhost:8080/static/imgs/events/" + file.Filename
			} else {
				data.Url = "http://114.115.208.52:8080/static/imgs/events/" + file.Filename
			}

			c.JSON(200, gin.H{
				"success": true,
				"message": "上传成功",
				// "url":     "/static/imgs/events/" + file.Filename,
				"url":   data.Url,
				"errno": 0,
				"data":  data,
			})
		} else {
			c.JSON(500, gin.H{
				"success": false,
				"errno":   1,
				"message": "上传失败",
			})
		}

	} else {
		c.JSON(500, gin.H{
			"success": false,
			"errno":   1,
			"message": "上传失败",
		})
	}

}

func (user Users) AddPicList(c *gin.Context) {
	title := c.PostForm("title")
	url := c.PostForm("src")
	isShow := c.PostForm("isShow")
	name := c.PostForm("name")
	timeNow := time.Now().Unix()
	timeNow2 := int(timeNow)
	pic := modules.Pic{
		Title:   title,
		Name:    name,
		Url:     url,
		IsShow:  isShow,
		AddTime: timeNow2,
	}

	modules.DB.Create(&pic)
	c.JSON(200, gin.H{
		"success": true,
		"message": "新增数据成功1",
	})
}

func (user Users) SwitchShow(c *gin.Context) {
	id := c.PostForm("id")
	isShow := c.PostForm("isShow")
	err := modules.DB.Model(&modules.Pic{}).Where("id=?", id).Update("is_show", isShow).Error
	if err == nil {
		c.JSON(200, gin.H{
			"success": true,
			"message": "修改成功",
		})
	} else {
		c.JSON(500, gin.H{
			"success": false,
			"message": "修改失败",
		})
	}
}
func (user Users) GetPicList(c *gin.Context) {
	page := c.DefaultQuery("page", "0")
	pageSize := c.DefaultQuery("pageSize", "10")
	title := c.DefaultQuery("title", "")
	pices := []modules.Pic{}
	p, _ := strconv.Atoi(page)
	s, _ := strconv.Atoi(pageSize)
	p = p - 1
	var count int64
	if title == "" {
		modules.DB.Limit(s).Offset(p * s).Find(&pices).Limit(-1).Offset(-1).Count(&count)
	} else {
		modules.DB.Where("Title LIKE ?", "%"+title+"%").Find(&pices).Limit(-1).Offset(-1).Count(&count)
	}
	c.JSON(200, gin.H{
		"list":     pices,
		"page":     page,
		"total":    count,
		"pageSize": pageSize,
	})
}
func (user Users) GetBannerList(c *gin.Context) {
	pices := []modules.Pic{}
	modules.DB.Where("is_show=?", "1").Find(&pices)
	c.JSON(200, gin.H{
		"list": pices,
	})
}
func (user Users) DeletePic(c *gin.Context) {
	id := c.Query("id")
	name := c.Query("name")
	num, _ := strconv.Atoi(id)
	pic := modules.Pic{
		Id: num,
	}
	modules.DB.Delete(&pic)
	json, _ := json.Marshal(pic)
	// println("pic.name--", name)
	// println("pic.Name", pic.Name)
	dsn := path.Join("./static/imgs/", name)
	err := os.Remove(dsn)
	println("err:", err)
	if err == nil {
		c.JSON(200, gin.H{
			"success": true,
			"message": "删除图片成功",
			"json":    string(json),
		})
	} else {
		c.JSON(200, gin.H{
			"success": false,
			"message": "删除图片失败",
		})
	}

}

func Int(timeNow int64) {
	panic("unimplemented")
}
